package com.hosp.controller.v1;


import java.util.ArrayList;
import java.util.List;

import com.github.pagehelper.PageInfo;
import com.hosp.bean.Role;
import com.hosp.controller.dto.RoleDTO;
import com.hosp.service.RoleService;
import com.hosp.vo.PageRequestVO;
import com.hosp.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 角色管理 API
 *
 * @author ztranscript 2021/9/23 22:11
 **/
@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    /**
     * 查询列表
     *
     * @param role        查询条件
     * @param pageRequest 分页条件
     * @return 响应
     */
    @GetMapping("/list")
    public ResultVO<Role> list(Role role, PageRequestVO pageRequest) {
        PageInfo<Role> pageInfo = roleService.list(role, pageRequest);
        return new ResultVO<>(pageInfo);
    }

    /**
     * 查询列表
     *
     * @param rId 查询条件
     * @return 响应
     */
    @GetMapping("/{rId}")
    public ResultVO<RoleDTO> selectById(@PathVariable("rId") Integer rId) {
        RoleDTO roleDTO = roleService.selectById(rId);
        return new ResultVO<>(roleDTO);
    }

    /**
     * 保存
     *
     * @param roleDTO 保存对象
     * @return 响应
     */
    @PostMapping("/save")
    public ResultVO<String> save(RoleDTO roleDTO) {
        log.debug("roleDTO is {}.", roleDTO);
        String mIds = roleDTO.getMIds();
        if (mIds != null) {
            List<Integer> mIdList = new ArrayList<>();
            String[] splStr = mIds.split(",");
            for (String s : splStr) {
                mIdList.add(Integer.valueOf(s));
            }
            roleDTO.setMIdList(mIdList);
        }
        log.debug("roleDTO is {}.", roleDTO);

        boolean flag = roleService.save(roleDTO);


        if (flag) {
            return new ResultVO<>(200, "保存成功");
        } else {
            return new ResultVO<>(500, "保存失败");
        }
    }

    /**
     * 删除
     *
     * @param rIdStr 待删除 IDs
     * @return 响应
     */
    @PostMapping("/delete")
    public ResultVO<String> delete(String rIdStr) {
        List<Integer> rIds = new ArrayList<>();
        String[] split = rIdStr.split(",");
        for (String s : split) {
            rIds.add(Integer.valueOf(s));
        }
        boolean flag = roleService.delete(rIds);

        if (flag) {
            return new ResultVO<>(200, "删除成功");
        } else {
            return new ResultVO<>(500, "删除失败");
        }
    }

}
